package com.gk.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Slf4j
@RestController
public class UserController {

    @Autowired
    private DiscoveryClient discoveryClient; //服务注册与发现客户端对象

    @Autowired
    private LoadBalancerClient loadBalancerClient; //负载均衡客户端对象

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("user")
    public String invokeDemo() {
        log.info("user demo...");
        //1. 调用订单服务 服务地址url：http://localhost:8889/order  get方式  接收返回值类型 String
/*
        RestTemplate restTemplate = new RestTemplate();
        String orderResult = restTemplate.getForObject("http://localhost:8889/order", String.class);
*/

        //2.使用ribbon组件+RestTemplate实现服务调用
/*        List<ServiceInstance> serviceInstances = discoveryClient.getInstances("ORDERS");
        serviceInstances.forEach(serviceInstance -> {
            log.info("服务主机：{} 服务端口：{} 服务地址：{}", serviceInstance.getHost(), serviceInstance.getPort(), serviceInstance.getUri());
        });
        String result = new RestTemplate().getForObject(serviceInstances.get(0).getUri() + "/order", String.class);*/

        //3.使用LoadBalancerClient进行负载均衡服务调用
/*        ServiceInstance serviceInstance = loadBalancerClient.choose("ORDERS");//负载均衡策略 默认使用 轮询
        log.info("服务主机：{} 服务端口：{} 服务地址：{}", serviceInstance.getHost(), serviceInstance.getPort(), serviceInstance.getUri());
        String result = restTemplate.getForObject("serviceInstance.getUri()" + "/order", String.class);*/
        //4.使用@LoadBalanced注解  作用：可以让对象具有ribbon负载均衡特性
        String result = restTemplate.getForObject("http://ORDERS//order", String.class);

        return "ok" + result;
    }
}
